#ifndef __TCP_SERVER__HPP
#define __TCP_SERVER__HPP

#include <iostream>
#include <string>
#include <cstring>
#include <memory>
#include <string.h>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/wait.h>
#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;

#define BACKLOG 8

const static int gsockfd = -1;
const static uint16_t gdefaultport = 8888;

using handler_t = std::function<std::string(std::string)>;

class TcpServer
{
public:
    TcpServer(handler_t handler, const uint16_t port = gdefaultport)
        :_listen_sockfd(gsockfd)
        ,_port(port)
        ,_isrunning(false)
        ,_handler(handler)
    {
        
    }

    void InitServer()
    {
        // 1.创建套接字
        _listen_sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if(_listen_sockfd < 0)
        {
            std::cout << "socket:" << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        std::cout << "socket success, _listen_sockfd is: " << _listen_sockfd << std::endl;
        
        // 2、填充网络信息，
        // 2.1 没有把socket信息，设置进如内核中，只是填充了结构体!
        struct sockaddr_in loacl;
        memset(&loacl, 0, sizeof(loacl));
        loacl.sin_family = AF_INET;
        loacl.sin_port = ::htons(_port); //要被发送给对方的，即要发送到网络中！
        loacl.sin_addr.s_addr = INADDR_ANY;
        //loacl.sin_addr.s_addr = ::inet_addr(_ip.c_str()); //1. 点分十进制转为整数 2. 转成网络字节序

        // 2.2 bind 设置如内核中
        int n = ::bind(_listen_sockfd, CONV(&loacl), sizeof(loacl));
        if(n < 0)
        {
            std::cout << "bind: "<< errno << " " <<strerror(errno) << std::endl;
            exit(BIND_ERR);
        }
        std::cout << "bind success" << std::endl;

        // 3.设置为监听状态
        int sockfd = ::listen(_listen_sockfd, BACKLOG);
        if(sockfd < 0)
        {
            std::cout << "listen: " << errno << " " << strerror(errno) << std::endl;
            exit(LISTEN_ERR);
        }
        std::cout << "listen success" << std::endl;
    }

    void HandleRequset(int sockfd)
    {
        char inbuffer[4096];
        while(true)
        {
            ssize_t n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                // 在后面字符串后面加上反斜杠0，以便于输出
                inbuffer[n] = 0;
                std::cout << "sockfd-" << sockfd << ": " << inbuffer << std::endl;

                // std::string echo_str = "echo# ";
                // echo_str += inbuffer;
                std::string cmd_result = _handler(inbuffer);
                ::send(sockfd, cmd_result.c_str(), cmd_result.size(), 0);
            }
            else if (n == 0)
            {
                std::cout << "client closed" << std::endl;
                break;
            }
            else
            {
                std::cout << "recv: " << errno << " " << strerror(errno) << std::endl;
                break;
            }
        }
        ::close(sockfd);
    }

    void Start()
    {
        _isrunning = true;
        while(true)
        {
            // 1.获取新连接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer); //必须设定

            std::cout << "waiting for connection..." << std::endl;
            int sockfd = accept(_listen_sockfd, CONV(&peer), &len);
            if(sockfd < 0)
            {
                std::cout << "accept: " << errno << " " << strerror(errno) << std::endl;
                continue;
            }
            std::cout << "accept success, new sockfd is: " << sockfd << std::endl;

            // 2.获取客户端信息
            char ipbuffer[64];
            const char *ip = ::inet_ntop(AF_INET, &peer.sin_addr, ipbuffer, sizeof(ipbuffer));
            std::string clientaddr = ip;
            clientaddr += ":";
            clientaddr += std::to_string(ntohs(peer.sin_port));
            std::cout << "client addr is: " << clientaddr << std::endl;

            // 3.处理请求
            //version 1 多进程模式 
            pid_t pid = fork();
            if(pid == 0)
            {
                ::close(_listen_sockfd); //子进程关闭监听套接字
                //
                if(fork() > 0) exit(0); // 子进程退出，父进程不用等待

                // 父进程->子进程退出->孙子进程，
                // 孙子进程会变成孤儿进程，由操作系统等待
                HandleRequset(sockfd);
                exit(0); //子进程退出
            }

            int rid = waitpid(pid, NULL, 0);
            if(rid < 0)
            {
                std::cout << "waitpid: " << errno << " " << strerror(errno) << std::endl;
            }

            // version 2 多线程模式
            // pthread_t tid;
            // pthread_create(&tid, NULL, [](void* arg){
            //     int sockfd = *(int*)arg;
            //     HandleRequset(sockfd);
            // }, (void*)sockfd);
            // pthread_detach(tid);
            
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listen_sockfd > gsockfd)
            ::close(_listen_sockfd);
    }
private:
    int _listen_sockfd;
    uint16_t _port;  //服务器端口号
    bool _isrunning; //服务器运行状态

    // 处理上层任务的入口函数
    handler_t _handler;
};

#endif